<template>
  <div class="warp">
    <div
      style="
        background-color: #233884;
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: #fff;
        font-size: 14px;
        height: 40px;
        padding: 0px 18px;
        width: 89%;
      "
    >
      <div>精细化网格</div>
      <div>
        <i class="el-icon-d-arrow-right" style="padding-right: 5px"></i>
      </div>
    </div>
    <div class="warp_top" style="margin-top: 1rem">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="时间" prop="dateChar">
          <el-date-picker
            v-model="form.dateChar"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="时次" prop="timeChar">
          <el-select v-model="form.timeChar" placeholder="请选择">
            <el-option
              v-for="item in options1"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时效" prop="nTimes">
          <el-select v-model="form.nTimes" placeholder="请选择">
            <el-option
              v-for="item in options2"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option
              v-for="(item, index) in options3"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <div class="flex-center">
          <el-button
            type="primary"
            style="margin-left: 10px"
            @click="showJxhMap"
            >{{ Mapviewing }}</el-button
          >
        </div>
      </el-form>
      <div class="warp_btn">
        <p>
          <el-button type="primary" @click="prevNtimes">上一时效</el-button>
          <el-button type="primary" @click="nextNtimes">下一时效</el-button>
        </p>
      </div>
      <!-- <div class="flex-row" style="margin-top: 1rem">
        <el-button style="margin-right: 10rem" @click="prevNtimes">时效-
          &lt;
        </el-button>
        <el-button style="margin-left: 10rem" @click="nextNtimes">时效+
          &gt;
        </el-button>
      </div> -->
      <!-- <div class="flex-center">
        <el-radio style="margin: 1rem 0" label="1"> 国标分级 </el-radio>
      </div> -->
      <div class="flex-colum">
        <el-button type="primary" @click="clearLayer">{{
          Clearaway
        }}</el-button>
        <el-button type="primary" @click="gedili">{{ Displaygrid }}</el-button>
        <el-button type="primary" @click="cleargedili">{{
          Cleargrid
        }}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { showGd, showMap } from "@/api/czyjyb.js";
import Boutn from "../button/button.vue";
export default {
  components: {
    Boutn,
  },
  props: {},
  data() {
    return {
      Mapviewing: "地图查看",
      extent: [106.2985, 23.981, 107.0091, 24.7318],
      Clearaway: "清除",
      Displaygrid: "显示格点",
      load: 0,
      markersData : [],
      Cleargrid: "清除格点",
      colorRange: [],
      gridData: [], //格网数据
      // 网格的行数和列数
      numCols: 72,
      // 密度，每3个显示1个
      step: 8,
      reducedDensityPoints9: "",
      reducedDensityPoints10: "",
      reducedDensityPoints11: "",
      reducedDensityPoints12: "",
      JxhURL: "",
      form: {
        dateChar: "2024-04-12",
        nTimes: "024",
        timeChar: "20",
        type: "温度",
        type1:"EDA10.V"
      },
      legendType: "",
      titleName:"",
      GridColor: "",
      rules: {
        dateChar: {
          required: true,
          message: "请选择日期",
          trigger: "change",
        },
        nTimes: {
          required: true,
          message: "请选择时效",
          trigger: "change",
        },
        timeChar: {
          required: true,
          message: "请选择时次",
          trigger: "change",
        },
      },
      options1: ["08", "20"], // 时次
      options2: ["024", "048", "072", "096", "120", "144", "168"], // 时效
      options3: [
        { label: "降水", value: "ER03" },
        { label: "湿度", value: "ERH" },
        { label: "温度", value: "TMP" },
        { label: "风速", value: "EDA10.U" },
        { label: "云量", value: "ECT" },
      ],
      yjJxhGridLayer: null, // 精细化网格图层
    };
  },
  methods: {
    initLayer() {
      //创建点图层
      this.yjJxhGridLayer =
        this.$store.state.map.qxMap.layer.createWebGLPointsLayer(
          "精细化网格",
          this.GridColor
        );
      console.log(this.yjJxhGridLayer, "网格图层");
    },
    showJxhMap() {
      this.clearAllLayer();
      this.typeJudge(this.form);
      console.log(this.legendType, "图例类型");
      this.$store.state.map.qxMap.layer.clearImgLayer("精细化预报");
      this.$emit("setLegend", {
        isImage: false,
      });
      showMap(this.form).then((res) => {
        let imageUrl = URL.createObjectURL(res.data);
        // console.log(imageUrl, "地图数据的URL");
        this.$store.state.map.qxMap.layer.setImgLayer(
          imageUrl,
          this.extent,
          "精细化预报"
        );
        //设置图例
        this.$emit("setLegend", {
          isImage: true,
          image: require(`@/assets/images/legend/${this.legendType}.png`),
        });
        let nTimes = "";
        if (this.form && this.form.nTimes) {
          // 首先将字符串转换为数组，这样可以通过索引访问每个字符
          let charArray = this.form.nTimes.split("");
          // 使用 filter 方法移除所有 '0' 字符
          let filteredArray = charArray.filter(function (char) {
            return char !== "0";
          });
          // 将过滤后的数组重新组合成字符串
          nTimes = filteredArray.join("");
        }
        //设置标题
        this.$emit("setTitle", {
          content: `${this.form.dateChar}${
            "日" + this.form.timeChar + "时" + " " + nTimes + "小时"
          }${this.titleName}图`,
          visable: true,
        });
      });
    },

    prevNtimes() {
      if (this.form.nTimes > 24) {
        this.form.nTimes = (this.form.nTimes - 24).toString().padStart(3, "0");
      } else {
        return;
      }
    },
    // @click="nextNtimes" 下一时效
    nextNtimes() {
      if (this.form.nTimes < 168) {
        this.form.nTimes = (this.form.nTimes - 0 + 24)
          .toString()
          .padStart(3, "0");
      } else {
        return;
      }
    },
    //判断加载类型
    typeJudge(form) {
      if (form.type == "温度" || form.type == "TMP") {
        this.legendType = "温度";
        this.titleName= "温度";
        form.type = "TMP";
      } else if (form.type == "雨量" || form.type == "ER03") {
        this.legendType = "雨量";
        this.titleName= "雨量";
        form.type = "ER03";
      } else if (form.type == "湿度" || form.type == "ERH") {
        this.legendType = "湿度";
        this.titleName= "湿度";
        form.type = "ERH";
      } else if (form.type == "风速" || form.type == "EDA10.U") {
        this.legendType = "风速";
        this.titleName= "风速";
        form.type = "EDA10.U";
        form.type1 = "EDA10.V";
      } else if (form.type == "云量" || form.type == "ECT") {
        this.legendType = "气压";
        this.titleName= "云量";
        form.type = "ECT";
      }
    },

    //格点显示
    gedili() {
      this.$emit("setLegend", {
        isImage: false,
      });
      this.$emit("setTitle", {
        visable: false,
      });
      this.load = 0;
      this.$store.state.map.qxMap.layer.clearImgLayer("精细化预报");
      this.typeJudge(this.form);
      showGd(this.form).then((res) => {
        if (res.status == 200) {
          // console.log(res.result.lons.length, "格点数量");
          this.gridData = res.result.lons.map((lon, index) => {
            return {
              lon: lon,
              lat: res.result.lats[index],
              value: res.result.vals[index],
            };
          });
          this.colorRange = res.total;

          this.clearAllLayer();
          // this.$store.state.map.qxMap.layer.fitExtentPaddingLayout(
          //               this.extent,
          //               700
          //       );
  // 填充 markersData 数组
        this.gridData.forEach((item) => {
          // 调用 getPointColor 方法获取颜色
          this.getPointColor(item.value);
          // 创建单个标记的数据对象
          let markerData = {
            lon: item.lon,
            lat: item.lat,
            color: this.GridColor, // 使用 GridColor 作为样式对象
          };
          // 将单个标记的数据对象添加到 markersData 数组
          this.markersData.push(markerData);
        });
        // console.log(this.markersData, "markersData");
          this.addGild();
          this.$store.state.map.qxMap.map.on("moveend", this.addGild);
        }
      });
      
    },
    //获取不同类型格点的颜色
    getPointColor(value) {
      this.GridColor =""
      // value=Math.abs(value);
      // 首先对colorRange数组根据elementvalue进行升序排序
      this.colorRange.sort((a, b) => a.elementvalue - b.elementvalue);
      // console.log(value ,"value");
      // 遍历排序后的数组
      for (let i = 0; i < this.colorRange.length - 1; i++) {
        // 如果value在当前元素的elementvalue和下一个元素的elementvalue之间
        if (
          value >= this.colorRange[i].elementvalue &&
          value < this.colorRange[i + 1].elementvalue
        ) {
          // 返回当前元素的elementcolor
          this.GridColor = `#${this.colorRange[i].elementcolor
            .toString(16)
            .padStart(6, "0")}`;
            
        }
      }
      // 如果value等于最大的elementvalue，返回最后一个元素的elementcolor
      if (value >= this.colorRange[this.colorRange.length - 1].elementvalue) {
        // this.GridColor = `#${this.colorRange[
        //   this.colorRange.length - 1
        // ].elementcolor
        //   .toString(16)
        //   .padStart(6, "0")}`;
        this.GridColor="#000"
      }
      //如果value小于最小的elementvalue，返回第一个元素的elementcolor
      if(value<this.colorRange[0].elementvalue){
        // this.GridColor = `#${this.colorRange[0].elementcolor
        //   .toString(16)
        //   .padStart(6, "0")}`;
        this.GridColor="#000"
      }
      // console.log( this.GridColor,"GridColor");
    },

    //地图添加圆点
    // addPoints(markersData, layer) {
    //   this.$store.state.map.qxMap.marker.addMarkers1(markersData, layer);
    // },
    //动态添加格点
    addGild() {
      const zoomLevel = this.$store.state.map.qxMap.map.getView().getZoom();
      console.log(zoomLevel, "zoom1231231");
      if (zoomLevel <= 13&&this.load!=12) {
        this.load = 12;
        this.clearAllLayer();
        // console.log(this.markersData, "markersData");
        this.$store.state.map.qxMap.marker.addMarkers1(
          this.markersData,
          this.yjJxhGridLayer
        );
      } else if (13 < zoomLevel &&this.load!=13 ) {
        this.load = 13;
       this.clearAllLayer();
        let color = "";
         console.log("load1313131313",this.load);
        this.gridData.forEach((item) => {
          //属性值
          this.$store.state.map.qxMap.marker.addText(
            [item.lon, item.lat],
            this.yjValueLayer,
            {
              name: `${item.value ? item.value : ""}`,
              fillColor: color,
              font: "normal 12px 微软雅黑",
              offsetX: 0,
              offsetY: 0,
            }
          );
        });
      }
    },
    //清除图层
    clearLayer() {
      this.$store.state.map.qxMap.layer.clearImgLayer("精细化预报");
      this.cleargedili();
      this.$emit("setLegend", {
        isImage: false,
      });
      this.$emit("setTitle", {
        visable: false,
      });
    },
    //清除格点
    cleargedili() {
      this.$store.state.map.qxMap.map.un("moveend", this.addGild);
       this.yjJxhGridLayer && this.yjJxhGridLayer.getSource().clear();
    },
    //创建所有的图层
    createAllLayer() {
      //创建点图层
      this.yjLayer =
        this.$store.state.map.qxMap.layer.createVectorLayer("站点图层");
      //创建点图层
      this.yjNameLayer =
        this.$store.state.map.qxMap.layer.createVectorLayer("站点名称图层");
      //创建点图层
      this.yjValueLayer =
        this.$store.state.map.qxMap.layer.createVectorLayer("数值图层");
      //创建点图层
      this.yjJxhGridLayer =
        this.$store.state.map.qxMap.layer.createWebGLPointsLayer(
          "精细化网格",
          this.GridColor
        );
      console.log(this.yjJxhGridLayer, "网格图层");
    },
    //移除地图资源
    clearAllLayer() {
      this.yjLayer && this.yjLayer.getSource().clear();
      this.yjNameLayer && this.yjNameLayer.getSource().clear();
      this.yjValueLayer && this.yjValueLayer.getSource().clear();
      this.yjJxhGridLayer && this.yjJxhGridLayer.getSource().clear();
    },
    removeAllLayer() {
      //移除图层
      this.yjLayer && this.$store.state.map.qxMap.map.removeLayer(this.yjLayer);
      this.yjNameLayer &&
        this.$store.state.map.qxMap.map.removeLayer(this.yjNameLayer);
      this.yjValueLayer &&
        this.$store.state.map.qxMap.map.removeLayer(this.yjValueLayer);
      this.yjJxhGridLayer &&
        this.$store.state.map.qxMap.map.removeLayer(this.yjJxhGridLayer);
      this.$store.state.map.qxMap.layer.clearImgLayer("精细化预报");
    },
  },
  mounted() {
    //创建所需图层
    this.createAllLayer();
    // this.initLayer();
  },
  destroyed() {
    this.$store.state.map.qxMap.map.un("moveend", this.addGild);
    this.removeAllLayer();
    this.$emit("setLegend", {
      isImage: false,
    });
    this.$emit("setTitle", {
      visable: false,
    });
  },
};
</script>

<style lang="scss" scoped>
.warp {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  .warp_title {
    width: 335px;
    height: 33px;
    background: #205cbc;
    display: flex;
    align-items: center;
    position: relative;
    .warp_span {
      color: #fff;
      margin-left: 15px;
      font-size: 15px;
    }
    .el-icon-d-arrow-right {
      color: #fff;
      position: absolute;
      right: 15px;
      width: 8px;
      height: 15px;
    }
  }
  .warp_btn {
    padding-left: 20px;
    width: 335px;
    height: 70px;
    p {
      display: flex;
      justify-content: space-evenly;
    }
  }
  .flex-center {
    display: flex;
    justify-content: center;
  }
  .flex-row {
    button {
      border-radius: 50%;
    }
  }
  .flex-colum {
    width: 335;
    height: 100px;
    display: flex;
    justify-content: space-around;
    button:nth-child(1) {
      margin-left: 10px;
    }
  }
  .el-form {
    display: flex;
    flex-direction: column;
    align-items: center;
    .el-form-item {
      width: 250px;
    }
  }
  ::v-deep .el-input--small .el-input__inner {
    width: 140px;
    height: 30px;
    line-height: 30px;
  }
  ::v-deep .el-select {
    width: 140px;
    height: 22px;
  }
  .el-button--small {
    padding: 5px 10px;
  }
  .el-button--primary {
    width: 70px;
    background-color: #1f5dbc;
    border-color: #1f5dbc;
  }
 
}
</style>
